package com.qiall.boot.util.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiall.boot.util.entity.PageListEntity;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Controller
public class PageController {

    @GetMapping("freemarkdatatrans")
    public String getUtil() {
        return "freemarkdatatrans";
    }

    @GetMapping("fileshare")
    public String fileShare() {
        return "fileshare";
    }

    @GetMapping("/")
    public String index(Model model) {
        List<PageListEntity> pageListEntities = new ArrayList<>();
        PageListEntity page = new PageListEntity();
        try {
            ClassPathResource classPathResource = new ClassPathResource("page.json");
            InputStream inputStream =classPathResource.getInputStream();

            String data = StreamUtils.copyToString(inputStream,Charset.forName("utf-8"));
            JSONArray jsonArray = JSON.parseArray(data);
            for (Iterator iterator = jsonArray.iterator(); iterator.hasNext(); ) {
                JSONObject obj = (JSONObject) iterator.next();
                String name = obj.get("name").toString();
                String url = obj.get("url").toString();
                PageListEntity pageListEntity=new PageListEntity();
                pageListEntity.setName(name);
                pageListEntity.setUrl(url);
                pageListEntities.add(pageListEntity);

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("pages", pageListEntities);
        return "index";
    }

    @GetMapping("treeParse")
    public String treeParse() {
        return "treeParse";
    }
}
